package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Employee;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    //新增
    @PostMapping
    public Result<?> save(@RequestBody User user) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        Date date = new Date();
        if (null != userService.selectByUsername(user.getUsername())) {
            return Result.error("-1", "用户名已存在,请重新输入");
        } else {
            //默认密码123456
            String aa =user.getPassword();
            if (!StrUtil.isNotBlank(user.getPassword())) {
                user.setPassword("123456");
            }
            if(!StrUtil.isNotBlank(user.getNickName())){
                user.setNickName(user.getUsername());
            }
            user.setCreatedTime(formatter.format(date));
            user.setUpdatedTime(formatter.format(date));
            userService.insert(user);
            return Result.success();
        }
    }


    //修改
    @PutMapping
    public Result<?> update(@RequestBody User user) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        Date date = new Date();
        user.setUpdatedTime(formatter.format(date));
        userService.updateById(user);
        return Result.success();
    }

    //删除
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        userService.deleteById(id);
        return Result.success();
    }

    //分页查询
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "3") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {

        Page<User> userPage = userService.selectPage(pageNum, pageSize, search);
        return Result.success(userPage);
    }

    @PutMapping("/updatePassword")
    public Result<?> updatePassowrd(@RequestBody User user){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        Date date = new Date();
        user.setUpdatedTime(formatter.format(date));
        userService.updatePassowrd(user);
        return Result.success();

    }
    @GetMapping("/getPassword")
    public Result<?> getPassword(@RequestParam int id, @RequestParam String password){
        int a=userService.getPassowrd(id,password);
        return Result.success(a);
    }
}
